<template>
  <div>
    <!-- 修改表单 -->
    <el-dialog title="修改书籍信息" :visible.sync="editFormVisible">
      <el-form :model="editForm">
        <el-form-item label="书本名字" :label-width="formLabelWidth">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者姓名" :label-width="formLabelWidth">
          <el-input v-model="editForm.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="editForm.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <img v-if="editVisible" width="200" :src="editForm.image"/>
        </el-form-item>
        <el-upload
            action="http://47.95.246.31:8080/book/upload/file"
            list-type="picture-card"
            limit='1'
            name="img"
            :on-preview="handlePictureCardPreview"
            :on-success="editSuccess"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="uploadDialogVisible">
            <img width="100%" :src="editForm.image" alt="">
        </el-dialog>
        <el-form-item label="书本简介" :label-width="formLabelWidth">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书本类别" :label-width="formLabelWidth">
          <el-select v-model="editForm.category.id" autocomplete="off">
              <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            editFormVisible = false;
            handleEidtChange();
          "
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 新增表单 -->
    <el-dialog title="新增书籍信息" :visible.sync="addFormVisible">
      <el-form :model="addForm">
        <el-form-item label="书本名字" :label-width="formLabelWidth">
          <el-input v-model="addForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者姓名" :label-width="formLabelWidth">
          <el-input v-model="addForm.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="addForm.price" autocomplete="off"></el-input>
        </el-form-item>

            <!-- action="http://localhost:8081/book/upload/file" -->
            <!-- action="http://47.95.246.31:8080/book/upload/file" -->
        <el-upload
            action="http://47.95.246.31:8080/book/upload/file"
            list-type="picture-card"
            limit='1'
            name="img"
            :on-preview="handlePictureCardPreview"
            :on-success="handleSuccess"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="uploadDialogVisible">
            <img width="100%" :src="addForm.image" alt="">
        </el-dialog>

        <el-form-item label="书本简介" :label-width="formLabelWidth">
          <el-input v-model="addForm.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书本类别" :label-width="formLabelWidth">
          <el-select v-model="addForm.category.id" autocomplete="off">
              <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="
            addFormVisible = false;
            handleAddChange();
          "
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <div class="tag-group" style="margin: 20px">
        <el-button plain @click="listBook()">
        所有图书
    </el-button>
    <span class="tag-group__title">书籍分类</span>
    <el-button plain v-for="tag in tags" :type="tag.type" :key="tag.name" :class="{ active: tag.isActive}" class="el-button--success" @click="listByTag(tag)">
        {{tag.name}}
    </el-button>
    </div>

    <el-row>
        <el-col :span="3" :offset="4">
            <el-input
                class="input-new-tag"
                v-if="tagInputVisible"
                v-model="tagInput"
                ref="saveTagInput"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
                >
                </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
        </el-col>
    </el-row>


    <el-table
      :data="
        tableData.filter(
          data =>
            !search || data.name.toLowerCase().includes(search.toLowerCase())
        )
      "
      ref="bookTable"
      stripe
      style="width: 100%"
      @selection-change="selsChange"
    >
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column width="50" label="图书编号" prop="id" align="center"> </el-table-column>
      <el-table-column width="150" label="书名" prop="name" align="center"> </el-table-column>
      <el-table-column width="80" label="作者" prop="author" align="center"> </el-table-column>
      <el-table-column width="50" label="价格" prop="price" align="center"> </el-table-column>
      <el-table-column width="150" label="封面" align="center">
          <template slot-scope="scope">
              <img :src="scope.row.image" style="height: 150px;width: 150px" alt="图书封面">
          </template>
      </el-table-column>
      <el-table-column width="500" label="图书简介" align="center">
          <template scope="scope">
              <div>
                  <p>{{scope.row.description}}</p>
              </div>
          </template>
      </el-table-column>

      <!-- <el-table-column
      align="right">
      <template slot="header" slot-scope="scope">
        <el-input
          v-model="search"
          size="mini"
          placeholder="输入关键字搜索"/>
      </template>
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
      </template>
    </el-table-column> -->
      <el-table-column label="操作" align="center">
        <!-- <template slot="header" slot-scope="scope">
        <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
      </template> -->
        <template scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="blog_table_footer">
      <el-button type="primary" size="mini" style="margin: 2px;" @click="handleAdd">新增
      </el-button>
      <el-button type="danger" size="mini" style="margin: 2px;" @click="deleteAll">批量删除
      </el-button>
    </div>
  </div>
</template>

<script>
import { postRequest } from "../utils/api";
import { putRequest } from "../utils/api";
import { deleteRequest } from "../utils/api";
import { getRequest } from "../utils/api";
import { myPostRequest } from "../utils/api";
import { base } from '../utils/api';
export default {
  methods: {
    selsChange(sels) {
        this.sels = sels;
    },
    listBook(tag) {
        var _this = this;
        let tags = this.tags;
        for(let i = 0;i < tags.length;i++) {
            tags[i].isActive = false;
        }
        if (JSON.stringify(tag) == "{}") {
            this.currentTag = null;
            getRequest('book/all').then(
                resp => {
                    if (resp.data.code == 0) {
                        _this.tableData = resp.data.data;
                    }
                }
            )
        } else {
            this.getBookByTag(tag);
        }
    },
    listByTag(tag) {
        // 是否进入方法
        // console.log('进入 listByTag');
        var _this = this;
        let tags = this.tags;
        this.currentTag = tag;
        // 重置所有tag
        for(let i = 0;i < tags.length;i++) {
            tags[i].isActive = false;
            tags[i].type = '';
        }
        // 修改样式
        tag.isActive = true;
        tag.type = "success";
        // tag
        // 发送远端请求
        this.getBookByTag(tag);
    },
    getBookByTag(tag) {
        var _this = this;
        // console.log("tagId = "+tag.id);
        postRequest('book/list', {
            category_id: tag.id
        }).then(resp => {
            if (resp.data.code == 0) {
                _this.tableData = resp.data.data;
            }
        });
    },
    addNewCate() {
      this.loading = true;
      var _this = this;
      postRequest("/admin/category/", { cateName: this.cateName }).then(
        resp => {
          if (resp.status == 200) {
            var json = resp.data;
            _this.$message({ type: json.status, message: json.msg });
            _this.cateName = "";
            _this.refresh();
          }
          _this.loading = false;
        },
        resp => {
          if (resp.response.status == 403) {
            _this.$message({
              type: "error",
              message: resp.response.data
            });
          }
          _this.loading = false;
        }
      );
    },
    deleteAll() {
      var _this = this;
      var checked = _this.$refs.bookTable.selection;
    //   console.log(checked);
    //   console.log(checked[0]);
      this.$confirm("确认删除这 " + checked.length + " 条数据?", "提示", {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          
        //   alert(checked.length);
          var ids = [];
          for (var i = 0; i < checked.length; i++) {
            ids.push(checked[i].bookId);
          }
          // TODO:发送请求删除
          // 直接刷新吧。。。。服了

        //   this.tableData
        })
        .catch(() => {
          //取消
          _this.loading = false;
        });
    },
    handleSelectionChange(val) {
      this.selItems = val;
    },
    handleAdd() {
        // 重置新增表单
        this.addForm = {
            id: "",
            name: "",
            author: "",
            num: 1,
            price: "",
            image: "",
            description: "",
            category: {},
        }
        this.addFormVisible = true;
    },
    handleAddChange(){
        var _this = this;
        myPostRequest('book/insert', this.addForm).then(
            resp => {
                if(resp.data.code == 0) {
                    _this.listBook(_this.currentTag);
                    // _this.tableData.push(_this.addForm);
                    _this.$message({
                        message: "书籍新增成功！",
                        type: 'success'
                    })
                } else {
                    _this.$message.error("书籍新增失败！");
                }
            }
        )
    },
    handleEdit(idx,row) {
      this.index = idx;
      this.editFormVisible = true;
      this.editForm = row;
      //   this.$prompt("请输入新名称", "编辑", {
      //     confirmButtonText: "更新",
      //     //   inputValue: row.cateName,
      //     inputValue: row.name,
      //     //   inputValue: row,
      //     cancelButtonText: "取消"
      //   }).then(({ value }) => {
      //     //value就是输入值
      //     if (value == null || value.length == 0) {
      //       _this.$message({
      //         type: "info",
      //         message: "数据不能为空!"
      //       });
      //     } else {
      //       _this.loading = true;

      //       putRequest("/admin/category/", { id: row.id, cateName: value }).then(
      //         resp => {
      //           var json = resp.data;
      //           _this.$message({
      //             type: json.status,
      //             message: json.msg
      //           });
      //           _this.refresh();
      //         },
      //         resp => {
      //           if (resp.response.status == 403) {
      //             _this.$message({
      //               type: "error",
      //               message: resp.response.data
      //             });
      //           }
      //           _this.loading = false;
      //         }
      //       );
      //     }
      //   });
    },
    handleEidtChange() {
        let _this = this;
        let book = this.tableData[this.index];
        myPostRequest('book/update', book).then(
            resp => {
                if(resp.data.code == 0) {
                    _this.$message({
                        message: '更新成功！',
                        type: 'success'
                    });
                    _this.getBookByTag(_this.currentTag);
                    // _this.tableData.splice(_this.index,1,_this.editForm);
                } else {
                    _this.$message.error('更新失败！');
                }
            }
        )
        // console.log(book);
    },
    handleDelete(index, row) {
      let _this = this;
      this.$confirm("确认删除 " + row.name + " ?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          postRequest('book/delete', {
              book_id: row.id
          }).then(
              resp => {
                  if(resp.data.code == 0) {
                      _this.$message({
                          message: "删除成功！",
                          type: "success"
                      });
                      _this.tableData.splice(index,1);
                  }
              }
          )
        })
        .catch(() => {
          //取消
          _this.loading = false;
        });
    },
    deleteCate(ids) {
      var _this = this;
      this.loading = true;
      this.tableData.splice(ids, 1);
      //删除
      deleteRequest("/admin/category/" + ids).then(
        resp => {
          var json = resp.data;
          _this.$message({
            type: json.status,
            message: json.msg
          });
          _this.refresh();
        },
        resp => {
          _this.loading = false;
          if (resp.response.status == 403) {
            _this.$message({
              type: "error",
              message: resp.response.data
            });
          } else if (resp.response.status == 500) {
            _this.$message({
              type: "error",
              message: "该栏目下尚有文章，删除失败!"
            });
          }
        }
      );
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
    },
    handleSuccess(response,file,fileList) {
        let _this = this;
        console.log(response);
        if(response.code == 0) {
            this.$message({
                message: '图片上传成功！',
                type: 'success'
            });
            let uri = response.msg;
            let url = base + uri;
            this.addForm.image = url;
            // this.uploadVisible = false;
        } else {
            this.$message.error(response.msg);
        }
    },
    editSuccess(response,file,fileList) {
        let _this = this;
        if(response.code == 0) {
            this.$message({
                message: '图片上传成功！',
                type: 'success'
            });
            let uri = response.msg;
            let url = base + uri;
            this.editForm.image = url;
            this.editVisible = false;
        } else {
            this.$message.error(response.msg);
        }
    },
    handlePictureCardPreview(file) {
        // this.addForm.image = file.url;
        this.uploadDialogVisible = true;
    },


    refresh() {
      let _this = this;
      getRequest("/admin/category/all").then(
        resp => {
          _this.categories = resp.data;
          _this.loading = false;
        },
        resp => {
          if (resp.response.status == 403) {
            _this.$message({
              type: "error",
              message: resp.response.data
            });
          }
          _this.loading = false;
        }
      );
    },
    showInput() {
        this.tagInputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

    handleInputConfirm() {
        let _this = this;
        let tagInput = this.tagInput;
        if (tagInput) {
            // console.log(tagInput);
            myPostRequest('category/insert', {
                id: null, name: tagInput, description: ""
            }).then(
                resp => {
                    if(resp.data.code == 0) {
                        _this.$message({
                            message: '添加分类成功！',
                            type: 'success'
                        });
                        getRequest('category/list').then(
                            resp => {
                                if (resp.data.code == 0) {
                                    _this.tags = resp.data.data;
                                }
                            }
                        )
                    }
                }
            )
        }
    this.tagInputVisible = false;
    this.tagInput = '';
    }
  },
  mounted: function() {
      //TODO
      console.log(base);
    var _this = this;
    this.loading = true;
    this.refresh();
    getRequest('category/list').then(
        resp => {
            if (resp.data.code == 0) {
                var tags = resp.data.data;
                for(let i = 0;i < tags.length;i++) {
                    Object.assign(tags[i], { isActive: false, type: '' });
                }
                _this.tags = tags;
            } else {
                _this.$message.error('数据加载失败！');
            }
        }
    );
    getRequest('book/all').then(
        resp => {
            if(resp.data.code == 0) {
                _this.tableData = resp.data.data;
            }
        }
    );
  },
  data() {
    return {
      index: 0,
      sels: [],
      currentTag: {},
      tagInputVisible: false,
      tagInput: '',
      cateName: "",
      selItems: [],
      categories: [],
      loading: false,
      tags: [
          { id: 1, name: 'JAVA', description: 'Java是目前最流行的语言之一' },
          { id: 2, name: 'Python', description: 'python比较简单' }
      ],
      tableData: [
        {
          id: "1",
          name: "javaweb入门基础",
          author: "张鹏",
          price: "50",
          image: null,
          description: "菜鸡",
          category: {
              id: 4,
              name: 'java编程'
          }
        },
      ],
      editForm: {
        id: "",
        name: "",
        author: "",
        number: null,
        image: null,
        price: "",
        category: {
              id: 0,
              name: ''
          }
      },
      addForm: {
        id: "",
        name: "",
        author: "",
        number: 1,
        image: null,
        price: "",
        category: {
              id: null,
              name: ''
          }
      },
      search: "",
      editFormVisible: false,
      addFormVisible: false,
      formLabelWidth: "120px",
      uploadDialogVisible: false,
      editVisible: true
    };
  }
};
</script>
<style>
.cate_mana_header {
  background-color: #ececec;
  margin-top: 20px;
  padding-left: 5px;
  display: flex;
  justify-content: flex-start;
}
.el-table {
  text-align: left;
}

.cate_mana_main {
  /*justify-content: flex-start;*/
  display: flex;
  flex-direction: column;
  padding-left: 5px;
  background-color: #ececec;
  margin-top: 20px;
  padding-top: 10px;
}

.blog_table_footer {
    float: right;
    display: flex;
    box-sizing: content-box;
    padding-top: 10px;
    padding-bottom: 0px;
    margin-bottom: 0px;
    justify-content: space-between;
  }

.wrap_one{
    overflow: hidden;
    -webkit-line-clamp: 4;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
}

.el-table__row{
    /* 不知道怎么调高度 */
    max-height: 100px;
    height: 100px;
}
</style>
